import requests
from typing import Dict, Any, Optional

from .config import SERVER_URL, WORKFLOW_KEYS, HEADERS

class DifyAPIError(Exception):
    """Dify API 异常"""
    pass

def run_workflow(
    workflow_name: str, 
    inputs: Dict[str, Any],
    user: str = "49",
    response_mode: str = "blocking"
) -> Dict[str, Any]:
    """
    运行 Dify 工作流

    Args:
        workflow_name: 工作流名称（"阶段总结" 或 "产业报告"）
        inputs: 输入参数字典
        user: 用户标识
        response_mode: 响应模式（streaming 或 blocking）

    Returns:
        Dict: 工作流执行结果

    Raises:
        ValueError: 工作流名称无效
        DifyAPIError: API调用失败
    """
    # 验证工作流名称
    if workflow_name not in WORKFLOW_KEYS:
        raise ValueError(f"无效的工作流名称: {workflow_name}")
    
    # 获取API key
    api_key = WORKFLOW_KEYS[workflow_name]["key"]
    
    # 构造请求URL和请求体
    url = f"{SERVER_URL}/workflows/run"
    payload = {
        "inputs": inputs,
        "response_mode": response_mode,
        "user": user
    }

    # 设置认证头
    headers = HEADERS.copy()
    headers["Authorization"] = f"Bearer {api_key}"
    print(headers)
    print(payload)
    try:
        # 发送请求
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        try:
            # 尝试解析响应体为JSON格式并打印
            print("Response JSON body:", response.json())
        except ValueError:
            # 如果响应体不是JSON格式，则直接打印文本内容
            print("Response body:", response.text)

        # 打印原始的异常信息
        print(f"Request error occurred: {e}")
        raise DifyAPIError(f"API调用失败: {e}")

def parse_workflow_response(response: Dict[str, Any]) -> str:
    """
    解析工作流响应（旧版本，兼容 text 字段）

    Args:
        response: 工作流执行结果

    Returns:
        str: 生成的文本内容

    Raises:
        ValueError: 响应格式无效
    """
    try:
        return response["data"]["outputs"]["text"]
    except KeyError:
        raise ValueError("无效的响应格式：无法找到 'data.outputs.text' 字段")

def parse_workflow_response1(response: Dict[str, Any]) -> str:
    """
    解析工作流响应（新版本，兼容 输出 字段）

    Args:
        response: 工作流执行结果

    Returns:
        str: 生成的文本内容

    Raises:
        ValueError: 响应格式无效
    """
    try:
        return response["data"]["outputs"]["输出"]
    except KeyError:
        raise ValueError("无效的响应格式：无法找到 'data.outputs.输出' 字段")

def upload_file(workflow_name, file_path, file_type):
    try:
        # 获取API key
        api_key = WORKFLOW_KEYS[workflow_name]["key"]
        headers = {
            "Authorization": f"Bearer {api_key}",
        }

        # 构造请求URL和请求体
        upload_url = f"{SERVER_URL}/files/upload"

        print(upload_url)
        print("上传文件中...")
        with open(file_path, 'rb') as file:
            files = {
                'file': (file_path, file, file_type)  # 确保文件以适当的MIME类型上传
            }
            data = {
                "user": 49,
                "type": file_type  # 设置文件类型为TXT
            }

            response = requests.post(upload_url, headers=headers, files=files, data=data)
            if response.status_code == 201:  # 201 表示创建成功
                print("文件上传成功")
                return response.json().get("id")  # 获取上传的文件 ID
            else:
                print(f"文件上传失败，状态码: {response.status_code}")
                return None
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return None

# 导出所有需要的函数和类
__all__ = ['run_workflow', 'parse_workflow_response', 'parse_workflow_response1', 'DifyAPIError', 'upload_file']